import gridHeader from './other/Fk_reim_modelwin.vue'
import tishi from './other/ts_message.vue'
import reimlist_upload from './other/reimlist_upload.vue'
import {
	h,
	resolveComponent
} from 'vue';
import {
	useRouter,
	useRoute
} from "vue-router"; //huangxs==2021年12月14日 15:33:24
import { ConsoleLogger } from '@microsoft/signalr/dist/esm/Utils';
//import { get_je_big } from "@/uitils/Utils.js";
import abc from "@/uitils/h_common.js";//这是默认的写法
//author:jxx
//此处是对表单的方法，组件，权限操作按钮等进行任意扩展(方法扩展可参照SellOrder.js)
var _alldata; //包括从服务器传来的所有数据
var _getcurr_reimid;
//var keyed=0;//如果等于1，说明可用额度超标；这个变量不用了，使用this.$store.getters.data().keyed=0;
var ed = 0;//防止有多条数据情况
var ti_num = 0;//提示超预算计数
let extension = {
	components: { //动态扩充组件或组件路径
		//表单header、content、footer对应位置扩充的组件
		gridHeader: gridHeader, //{ template: "<div>扩展组xx件</div>" },
		gridBody: '',
		gridFooter: '',
		//弹出框(修改、编辑、查看)header、content、footer对应位置扩充的组件
		modelHeader: reimlist_upload,
		modelBody: tishi,
		modelFooter: {
			render() {
				return [
					h(resolveComponent('el-alert'), {
						style: {
							'margin-bottom': '12px'
						},
						'show-icon': true,
						type: 'warning',
						closable: false,
						title: '桔红色金额为超预算或没有预算'
					}, ''),
				]
			}
		},
	},
	//tableAction: "fk_reim?r_type=only",//菜单增加参数时需要添加
	buttons: {
		view: [],
		box: [],
		detail: []
	}, //扩展的按钮
	methods: { //事件扩展
		onInit() {
			//let router = useRouter();//huangxs==2021年12月14日 15:33:24如何给跳转路由加参数
			//console.log(router.currentRoute._rawValue.hash);//huangxs==2021年12月14日 15:33:24
			//old_editFormOptions=this.editFormOptions;

			//console.log(this.editFormOptions)
			this.maxBtnLength = 15;
			//隐藏查询界面按钮
			this.buttons.forEach(x => {
				// console.log(x)
				if (x.name == "查 询" || x.name == "编 辑") {
					x.hidden = true;
					//this.$set(x, "hidden", true);
				}
			})

			//this.columnIndex = true;主表序号显示
			this.detailOptions.columnIndex = true; //从表序号显示
			this.add_delimit(this.editFormOptions);//插入分割栏

			//console.log(this.columns);
			this.editFormOptions.forEach(x => {
				x.forEach(item => {
					if (item.field == 'fujian') {
						//多文件上传，两个属性要同时用才能器效果huangxs
						item.multiple = true;
						item.maxFile = 3;
					}
				})
			});

			this.summary = true; //主表合计	
			this.detailOptions.summary = true; //设置子表合计

			this.editFormOptions.forEach(x => {//设为只读为了方便自动填写
				x.forEach(item => {
					if (item.field == 'fkcontent') {
						item.readonly = true;
					}
				})
			})

		},

		onInited() {

			//移除快捷查询
			this.singleSearch = null;
			this.boxOptions.labelWidth = 120;
			//console.log(this.$refs);
			//设置主表求字段，后台需要实现SummaryExpress方法
			this.detailOptions.columns.forEach(x => {
				if (x.field == 'je') {
					x.summary = true; //合计

					x.cellStyle = (row, rowIndex, columnIndex) => { //相当于给X增加属性 cellStyle

						let _tt = _alldata.extra.ys_query.find(x => {
							return x.racct === row.fei_type && x.rcntr === row.rcntr
						});
						//console.log(row.fei_type);
						if (_tt === undefined) {//没有查询到预算说明也是没预算的所以要红色
							//this.$message.error('没有相关预算数据！')
							return {
								background: "#ff5500"
							}
						} else {
							if (row.je > _tt.kyed) {
								//console.log(ti_num);
								if (ti_num <= 1) {
									this.$message.error("超预算，预算可用额度为" + _tt.kyed)
									ti_num = ti_num + 1
								}

								//this.$refs.modelBody._message="超预算，预算可用额度为"+_tt.kyed
								//keyed=1;
								ed = 1;
								//this.$store.getters.data().keyed=1;
								return {
									background: "#ff5500"
								}
							} else {
								this.$store.getters.data().keyed = 0;//没有超预算再改回来；
								//keyed=0;
							}
							if (ed == 1) this.$store.getters.data().keyed = 1;//超预算

						}
					}
				}
			});

			this.detail_init();
			/* this.detailOptions.columns.forEach(x => { //成本中心与科目两个下拉表关联关系,这里有bug,当前行变更会影响其他行
				if (x.field == 'rcntr') {
					x.onChange = (row, column, value) => { //给成本中心字段增加onChange事件
						//console.log(row)
						var turl = "/api/Fk_reim/get_fei_for_cntr?rcntr=" + row.rcntr;
						this.http.post(turl, {}, true).then((s) => {
							let _index = this.detailOptions.columns.findIndex(x => {
								return x.field == 'fei_type'
							});
							//console.log(this.detailOptions);
							this.detailOptions.columns[_index].bind.data = s.rtn_hst_q;
						});

					}
				};
			}); */

		},
		modelOpenAfter(row) {
			ti_num = 0;//提示超预算计数清零
			if (this.currentAction == "Add") { //只有新增数据的界面才给初始值
				this.editFormFields.bdatetime = _alldata.extra.currdate; //注意给新增界面字段赋初始值，一定要在modelOpenAfter()事件中；
				this.editFormFields.username = _alldata.extra.username;
				//console.log(_alldata)
				this.editFormFields.depid_oa = _alldata.extra.depid_oa;
				this.editFormFields.typeid = 1;
			}
			//this.$refs.modelBody._message=this.editFormFields.reim_id
			this.set_modelBody();
			if (row === undefined) {
			} else {
				this.quan_control(row);
			}
			//console.log(row);
			/* console.log(this.editFormOptions);
			console.log(this.editFormFields);
			console.log(this.detailOptions);
			console.log(this.buttons);
			console.log(this.boxButtons);//弹出窗体按钮 */
			this.autofill(this.currentAction);
		},
		searchDetailAfter(data) {
			//console.log(this.dicKeys)
			//console.log(data[0])
			return true;
		},

		quan_control(row) {//控制界面viewgrid只读，只能放在modelOpenAfter事件中
			//console.log(row)
			//因为弹出窗体不刷新，先改成可以编辑，然后在根据权限判断哪些可以编辑2022年3月22日 09:27:22 by huangxs
			if (row.stepid == 1) {//满足条件开启编辑
				this.detailOptions.edit = true;
				this.detailOptions.buttons.forEach(x => {//明细表的按钮隐藏
					x.hidden = false;
				});
				this.boxButtons.forEach(x => {
					x.hidden = false;
				});
				this.editFormOptions.forEach(x => {
					x.forEach(item => {
						//item.disabled=true;

						if (_alldata.extra.tb_list.some(s => s == item.field)) {//对比后台是否可编辑字段
							//console.log(item.disabled)
							item.disabled = false
						}

						//
					})
				});
			}
			//console.log(_alldata.extra.tb_list);


			//以下根据权限stepid修改界面的是否只读
			if (row.stepid > 1 || (row.stepid == 1 && (this.$store.getters.data().curr.username != row.username))) {
				//满足条件变为只读，提交后或者没有提交前但是是协同人员，不可编辑
				this.editFormOptions.forEach(x => {
					x.forEach(item => {
						//item.disabled=true;
						if (row.stepid == 6 && item.field == "check_je") {//除了这些情况允许填写,stepid=6财务初审可以填入财务审核金额
							item.disabled = false;//开启可填
						} else {
							item.disabled = true;//不可填
						}
						//
					})
				});

				this.detailOptions.buttons.forEach(x => {//明细表的按钮隐藏
					x.hidden = true;
				});
				this.detailOptions.edit = false;
				this.boxButtons.forEach(x => {//弹出窗体按钮
					if (row.stepid == 6) {
						x.hidden = false;//除了这些情况允许填写,stepid=6财务初审可以填入财务审核金额
					} else {
						x.hidden = true;
					}

				})
			}
		},
		set_modelBody() {//注意框架自带的modelBody在打开model窗体时不能更新，所以只能在父窗体对modelBody状态进行赋值*****huangxs 2022年3月15日 16:29:32

			this.$refs.modelBody.get_init_page(this.editFormFields.reim_id);//get_init_page子之间的方法，让父调用
		},
		searchBefore(param) { //查询ViewGird表数据前,param查询参数
			//添加其他查询条件,也可以在后台扩展中写查询条件
			let wheres = [{
				'name': 'typeid',
				'value': '1',//1费用报销,2为差旅报销
				//'displayType': 'like'//设置为模糊查询,其他不需要设置
			}]
			//也可以提交一些其他参数，后台在GetPageData()方法读取options.value
			//param.value = "xxx";

			param.wheres.push(...wheres);
			//返回false，则不会执行查询
			return true;
		},
		exportBefore(formData) {
			formData.wheres.push(
				{
					'name': 'typeid',
					'value': '1',
				}
			)//1费用报销,2为差旅报销
			//console.log(formData)
			return true;
		},
		searchAfter(result, alldata) { //查询ViewGird表数据后param查询参数,result回返查询的结果
			_alldata = alldata; //查询后从服务器传入所有数据  huangxs
			this.$store.getters.data().curr = { username: _alldata.extra.username };//存当前登录，给子窗体用
			//this.$store.getters.data().rf_sqj=_alldata.rf_sqj;//用于计算申请解除可用额度限制状态的判断
			this.$store.getters.data()._alldata = _alldata;
			//console.log(_alldata);
			//console.log("after");
			return true;
		},

		addRow() {
			//明细表添加行，在此处可以设置添加的默认值
			let obj = {};
			//给明细表添加行时，设置默认值。--onInited方法中对this.detailOptions.columns进行formatter也可以实现)

			obj.xh = this.$refs.detail.rowData.length + 1; //序号增加1

			this.$refs.detail.addRow(obj);
		},

		delBefore(ids, rows) { // 主表，查询界面的表删除前 ids为删除的id数组,rows删除的行
			//console.log(rows)//x.username案件起草人
			//console.log(_alldata.extra.username)//当前登录的用户名
			//some表示找到满足里面条件的数据
			let quanx = rows.some(x => {
				return (x.username.indexOf(_alldata.extra.username) == -1)
			}); //流程权限控制
			//console.log(quanx);
			if (quanx) { //只要有一个step_username！=loginid，就不允许删除
				this.$message.error('不具备删除的权限！')
				return false;

			}
			return true; //正常须返回true;

		},

		updateBefore(formData) {
			this.autofill2(formData);
			/* if (this.currentAction == "update" && formData.mainData.username.indexOf(_alldata.extra.username) == -
				1) //流程权限控制
			{
				this.$message.error('不具备保存权限！')
				return false;
			} */
			return true;
		},
		addBefore(formData) { //新建保存前formData为对象，包括明细表
			this.autofill2(formData);
			//this.$message.success("ddd");
			return true;
		},
		rowClick({
			row,
			column,
			event
		}) { //查询界面table点击行选中当前行
			//取消其他行选中
			this.$refs.table.$refs.table.clearSelection();
			//设置选中当前行
			this.$refs.table.$refs.table.toggleRowSelection(row);
		},

		tijiao() { //打开提交窗口。viewgrid自定义按钮的定义在config/buttons.js中(huangxs2021年12月2日 16:01:48)
			/* if (this.$store.getters.data().keyed==1){
				this.$message.error("预算超标");
			} */
			let rows = this.$refs.table.getSelected();
			if (rows.length == 0)
				return this.$error("请选择要审核的行!");
			//_getcurr_reimid=10;
			//console.log(rows)
			this.$store.getters.data().curr_reim = {
				reim_id: rows[0].reim_id,
				stepid: rows[0].stepid
			}; //通过全局变量存跨页面数据
			let _i = rows.findIndex(t => { return t.stepid == 9 });
			if (_i >= 0) {
				this.$message.error("归档的案件不能提交！")
			} else {//小于0表示没有归档的案件
				this.$refs.gridHeader.open3(rows);
			}
		},
		add_delimit(editFormOptions) {//插入分割栏
			var obj = {
				colSize: 12,
				render: (h) => {
					return h(resolveComponent('el-alert'), {
						style: {

						},
						'show-icon': true,
						type: 'warning',
						closable: false,
						title: '以下为付款信息'
					});
				}
			};
			editFormOptions[2].splice(0, 0, obj);//
		},
		autofill(ls_type) {
			this.$nextTick(() => {
				this.editFormOptions.forEach(item => {
					item.forEach(x => {
						//增加默认值
						if (x.field == "biz") {
							//editFormOptions.biz="人民币";
							if (ls_type == "Add") this.editFormFields.biz = x.data[0].key;
						}
					})

				})
			});
			//console.log(editFormOptions);
		},
		autofill2(formdata) {//字段之间赋值
			//console.log(formdata)
			var rcntr;
			var km;
			var jsonObj=JSON.stringify(formdata);
			//console.log(jsonObj)
			//return;
			if (jsonObj.indexOf("rcntr")>0){
				var dic = this.dicKeys.filter((x) => {//从字典中取对应的中文
					return x.dicNo == 'cntr';
				});
				var v = dic[0].data.filter((x) => {
					return x.key == formdata.detailData[0].rcntr;
				})[0].value
				rcntr = v.split(" ")[0];
				dic = this.dicKeys.filter((x) => {
					return x.dicNo == 'fei_typelist';
				});
				var v = dic[0].data.filter((x) => {
					return x.key == formdata.detailData[0].fei_type;
				})[0].value
				km = v.split(" ")[0];
				formdata.mainData.fkcontent = this.editFormFields.username + " 报 " + rcntr + " " + this.editFormFields.fsny + " 发生 " + km + "--" + this.editFormFields.kxprop;
				formdata.mainData.yk_je_big = abc.get_je_big(this.editFormFields.yk_je);
				formdata.mainData.sf_je_big = abc.get_je_big(this.editFormFields.sf_je);
				formdata.mainData.check_je_big = abc.get_je_big(this.editFormFields.check_je);
				formdata.mainData.total_j_big = abc.get_je_big(this.editFormFields.total_j);
			}
			
		},

		detail_init() {
			this.detailOptions.columns.forEach(x => {
				//console.log(this.detailOptions.columns[6]);
				if (x.field == 'je') {//合计需要前后端都要计算
					x.summary = true; 
				}
				if (x.field == 'tax' ) {
					x.summary = true; 
				}
				if ( x.field == 'ws_je') {
					x.summary = true; 
				}
				if (x.field == 'ws_je') {//自动计算ws_je字段
					let je = 0;
					let tax = 0;
					x.formatter = (row) => {
						if (row.je > 0) je = row.je;
						if (row.tax > 0) tax = row.tax;

						row.ws_je = Number(je) - Number(tax);
						//row.je=row.tax;
						return row.ws_je;
					}
				}

			});
			let _index = this.detailOptions.columns.findIndex(x => { return x.field == 'fujian' });
			//从表动态添加一列(上传图片列),生成上传图片、与删除图片操作
			this.detailOptions.columns.splice(_index+1, 0, {
				field: "随便写",
				title: "上传票据",
				width: 150,
				align: "center",
				render: (h, { row, column, index }) => {
				  //下面所有需要显示的信息都从row里面取出来
				  return h(
					"div", { style: { color: '#0c83ff', 'font-size': '13px', cursor: 'pointer' } },
					[
					  h(
						"i", {
						style: { 'margin-right': '10px' },
						class:['el-icon-upload'],
						onClick: (e) => {
						  e.stopPropagation();
						  //记住当前操作的明细表行数据
						  //如果原来有图片,上传图片界面把原来的图片也显示出来
						  let fileInfo = (row.fujian || '').split(",").filter(x => { return x }).map(img => {
							//(生成文件格式) fileInfo格式参数，见volupload组件
							return { path: img, name: "" };
						  })
						  this.$refs.modelHeader.open(fileInfo, row)
						}
					  }, [], '上传'
					  ),
					  h('i', {
						style: { 'margin-right': '10px' },
						class: ['el-icon-delete'], onClick: (e) => {
						  e.stopPropagation(); row.fujian = ''
						}
					  }, '删除'),
					])
				},
			  })
			  //从表动态添加一列(上传图片列),生成上传图片、与删除图片操作
			this.detailOptions.columns.splice(_index+2, 0, {
				field: "随便写",
				title: "OCR",
				width: 200,
				align: "center",
				render: (h, { row, column, index }) => {
				  //下面所有需要显示的信息都从row里面取出来
				  return h(
					"div", { style: { color: '#0c83ff', 'font-size': '13px', cursor: 'pointer' } },
					[
					  h(
						"i", {
						style: { 'margin-right': '10px' },
						class:['el-icon-lightning'],
						 onClick:async (e) => {
						  e.stopPropagation();  
						  await  this.http.get("/api/customer/vatInvoice?fileNamePath="+row.fujian).then(x => {
							if (x.status){//
								var tt=JSON.parse(x.data.fpstr);
								var jsonObj=JSON.stringify(tt);
								//console.log(jsonObj.indexOf("words_result"));
								//console.log(jsonObj.indexOf("error_code"));
								if (jsonObj.indexOf("error_code")>0){//判读json是否有这个属性
									this.$message.error("OCR失败，请重新上传附件");
								}
								if (jsonObj.indexOf("words_result")>0){
									row.tickno=tt.words_result.InvoiceNum
									row.je=tt.words_result.AmountInFiguers
									row.tax=tt.words_result.TotalTax
									row.ws_je=tt.words_result.TotalAmount
									row.fzdate=tt.words_result.InvoiceDate
									this.$message.success("OCR成功！");
								}
								
							}else{//失败
								this.$message.error(x.message);
								//this.openid=x.message;
							}
						});
						
						}
					  }, [], '增值税票OCR'
					  ),
					  h('i', {
						style: { 'margin-right': '10px' },
						class: ['el-icon-guide'], 
						onClick: (e) => {
							this.$message.error("验真未开通！");
						}
					  }, '验真'),
					])
				},
			  })
		}
	}
};
export default extension;
